package com.linkvin.ec.hcs.service.account.impl;

import com.google.common.base.Strings;
import com.linkvin.ec.hcs.dao.mapper.sysadmin.AccountMapper;
import com.linkvin.ec.hcs.dao.mapper.sysadmin.AccountUserMapper;
import com.linkvin.ec.hcs.dao.mapper.sysadmin.UserMapper;
import com.linkvin.ec.hcs.dao.model.sysadmin.Account;
import com.linkvin.ec.hcs.dao.model.sysadmin.User;
import com.linkvin.ec.hcs.dao.model.sysadmin.bo.AccountUserBo;
import com.linkvin.ec.hcs.service.account.AccountService;
import com.linkvin.ec.hcs.service.security.config.PasswordEncoderConfig;
import com.linkvin.ec.hcs.service.security.domains.JwtUser;
import com.linkvin.ec.hcs.service.security.util.JwtTokenUtil;
import com.linkvin.ec.hcs.service.util.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * Created by zhaoguixin on 2017/11/28.
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AccountUserMapper accountUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountMapper accountMapper;


    @Autowired
    private AuthenticationManager authenticationManager;


    @Override
    public AccountUserBo getAccountInfo() {
        try {
            JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            AccountUserBo accountUserBo = accountUserMapper.selectAcUserByAcCode(authUser.getAccountCode());
            if (Objects.equals(accountUserBo, null)) {
                throw new BaseException("账号不存在");
            } else {
                if (accountUserBo.getRoles() == null || accountUserBo.getRoles().isEmpty()) {
                    //TODO 处理用户没有角色的问题，要分配一个默认"访客"角色
//                    accountUserBo.setRoles(new List<String>["admin"]);
                }
                return accountUserBo;
            }
        } catch (Exception e) {
            throw e;
        }
    }


    @Override
    public String accountLogin(String userKey, String password) {

        if (Strings.isNullOrEmpty(userKey)) throw new BaseException("用户标识不能为空！");
        if (Strings.isNullOrEmpty(password)) throw new BaseException("密码不能为空！");

        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userKey, password);
        final Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        if (authentication.isAuthenticated()) {
            JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
            return jwtTokenUtil.buildHeadToken(jwtUser);
        } else {
            throw new BaseException("用户名或密码错误！");
        }

    }

    @Override
    public Boolean accountLogout() {
        boolean blnRtn = false;
        try{
            SecurityContextHolder.clearContext();
            blnRtn = true;
        }
        catch (Exception ex){
            throw new BaseException(ex.getMessage());
        }
        return  blnRtn;

    }

    @Override
    public Boolean examinPassword(String password) {

        boolean blnRtn = false;

        JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String accountCode = authUser.getAccountCode();

        try{
            UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(accountCode, password);
            final Authentication authentication = authenticationManager.authenticate(upToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            blnRtn = authentication.isAuthenticated() ;

        }
        catch (BadCredentialsException ex){
            throw new BaseException(10003,ex.getMessage());
        }
        catch (Exception ex) {
            throw new BaseException(ex.getMessage());

         }

        return blnRtn;

    }

    @Override
    public Boolean updatePwd(String password) {
        boolean blnRtn = false;

        JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int accountId = authUser.getAccountId();

        try{

            Account account = new Account();
            account.setId(accountId);
            String newPassword = PasswordEncoderConfig.passwordEncoder().encode(password);
            account.setPwd(newPassword);
            accountMapper.updateById(account);
            blnRtn = true;
        }
        catch (Exception ex) {
            throw new BaseException(ex.getMessage());

        }

        return blnRtn;
    }


}
